<?php
use Illuminate\Database\Eloquent\SoftDeletingTrait;

class Product extends Eloquent
{
	use SoftDeletingTrait;

	public $timestamps   = true;
	protected $dates     = ['deleted_at'];
	protected $table     = 'product';
	protected $validator = null;

	public function saveData($data)
	{
		$product = new Product;

		if(isset($data['id'])){
			$product = Product::firstOrCreate(array('id' => $data['id']));
		}
		
		$product->name    	= $data['name'];
		$product->net     	= $data['net'];
		$product->brand     = $data['brand'];
		$product->type     	= $data['type'];
		$product->price     = $data['price'];
		$product->quantity	= $data['quantity'];

		$product->save();

		return $product;
	}

	public function getDatas($page = 0, $limit = 10)
	{
		$products = Product::all();

		return $products;
	}

	public function scopeProducts($query, $type = 'all'){
		if($type != 'all'){
			$result = DB::table('product as p')
			->join('taxonomy as tb', 'tb.id', '=', 'p.brand')
			->join('taxonomy as tt', 'tt.id', '=', 'p.type')
			->select('p.id', 'p.name', 'p.net', 'p.price', 'p.quantity', 'p.created_at', 'p.updated_at', 'tb.taxonomy as brand', 'tt.taxonomy as type')
			->where('p.deleted_at', '=', NULL)
			->where('p.type', '=', $type)
			->orderBy('tb.order')
			->get();
		}else{
			$result = DB::table('product as p')
						->join('taxonomy as tb', 'tb.id', '=', 'p.brand')
						->join('taxonomy as tt', 'tt.id', '=', 'p.type')
						->select('p.id', 'p.name', 'p.net', 'p.price', 'p.quantity', 'p.created_at', 'p.updated_at', 'tb.taxonomy as brand', 'tt.taxonomy as type')
						->where('p.deleted_at', '=', NULL)
						->orderBy('tb.order')
						->get();
		}

		return $result;
	}

	public function validator($data)
	{
		$id = (isset($data['id']))? $data['id'] : "NULL";

		$rules = array(
				'name' => 
					array(
						'required', 
						'unique:product,name,' . $id . ',id,net,' . $data['net'] . ',brand,' . $data['brand'] . ',type,' . $data['type'] . ',deleted_at,NULL',
						'alpha_num_spaces',
					),
				'net' => 
					array(
						'alpha_num',
					),
				'price' => 
					array(
						'required', 
						'numeric',
					),
				);

		$this->validator = Validator::make($data, $rules);

		return $this->validator;
	}

	public function getValidatorMessage(){
		$messages = $this->validator->messages();
		
		$result   = array();

		foreach($messages->all() as $m){
			$result[]['message'] = $m;
		}

		return $result;
	}
}